package com.example.kaptcha.controller;

import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
import javax.servlet.http.HttpSession;
import java.util.Date;
 
@RequestMapping("/admin")
@RestController
public class CaptchaController {
    private static final String KAPTCHA_SESSION_KEY = "HOME_KAPTCHA_SESSION_KEY";
    private static final String KAPTCHA_SESSION_DATE = "HOME_KAPTCHA_SESSION_DATE";

    private static final Long SESSION_TIMEOUT = 60 * 1000L;

    @RequestMapping("/check")
    public Boolean check(String captcha, HttpSession session) {
       if(!StringUtils.hasLength(captcha)) {
           return false;
       }
       String saveCaptcha = (String) session.getAttribute(KAPTCHA_SESSION_KEY);
       Date saveDate = (Date) session.getAttribute(KAPTCHA_SESSION_DATE);
       if(saveCaptcha.equals(captcha)) {
           if(saveDate != null && System.currentTimeMillis() - saveDate.getTime() < SESSION_TIMEOUT) {
               return true;
           }
       }
        return false;
    }
}